package com.ruoyi.oa.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.oa.domain.OaHumanClockTotal;
import com.ruoyi.oa.domain.bo.OaHumanSelectMonthBo;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.oa.domain.vo.OaHumanClockCountVo;
import com.ruoyi.oa.domain.bo.OaHumanClockCountBo;
import com.ruoyi.oa.service.IOaHumanClockCountService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 考勤记录
 *
 * @author ruoyi
 * @date 2023-07-19
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/oa/humanClockCount")
public class OaHumanClockCountController extends BaseController {

    private final IOaHumanClockCountService iOaHumanClockCountService;

    /**
     * 查询考勤记录列表
     */
//    @SaCheckPermission("oa:humanClockCount:list")
    @GetMapping("/list")
    public TableDataInfo<OaHumanClockCountVo> list(OaHumanClockCountBo bo, PageQuery pageQuery) {
        return iOaHumanClockCountService.queryPageList(bo, pageQuery);
    }


    @GetMapping("/queryPerDaySum")
    public TableDataInfo<OaHumanClockCountVo> queryPerDaySum(OaHumanClockCountBo bo, PageQuery pageQuery){
        return iOaHumanClockCountService.queryPerDaySum(bo, pageQuery);
    }


    /**
     * 通过月份以及用户id获取用户当月打卡条数
     * @param userId
     * @param month
     * @return
     */
    @GetMapping("/getUserClockCountByMonth")
    public R<Integer> getUserClockCountByMonth(@RequestParam(value = "userId", required = false) String userId,
                                                @RequestParam(value = "month", required = false) String month){
        return R.ok(iOaHumanClockCountService.getUserClockCountByMonth(userId,month));
    }

    /**
     * 获取某人本月外勤次数
     * @param userId
     * @param month
     * @return
     */
    @GetMapping("/getOutSideCount")
    public R<Integer> getOutSideCount(@RequestParam(value = "userId", required = false) String userId,
                                               @RequestParam(value = "month", required = false) String month){
        return R.ok(iOaHumanClockCountService.getOutSideCount(month,userId));
    }



    @GetMapping("/getLeaveCount")
    public R<Integer> getLeaveDate(@RequestParam(value = "userId", required = false) String userId,
                                      @RequestParam(value = "month", required = false) String month){
        return R.ok(iOaHumanClockCountService.getLeaveCount(month,userId));
    }

    @GetMapping("/getLeaveData")
    public R<List<OaHumanClockCountVo>> getLeaveData(@RequestParam(value = "userId", required = false) String userId,
                                   @RequestParam(value = "month", required = false) String month){
        return R.ok(iOaHumanClockCountService.getLeaveData(month,userId));
    }

    /**
     * 导出考勤记录列表
     */
//    @SaCheckPermission("oa:humanClockCount:export")
    @Log(title = "考勤记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(OaHumanClockCountBo bo, HttpServletResponse response) {
        List<OaHumanClockCountVo> list = iOaHumanClockCountService.queryList(bo);
        ExcelUtil.exportExcel(list, "考勤记录", OaHumanClockCountVo.class, response);
    }


    @Log(title = "日报考勤记录", businessType = BusinessType.EXPORT)
    @PostMapping("/perDayExport")
    public void perDayExport(OaHumanClockCountBo bo, HttpServletResponse response){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        List<OaHumanClockCountVo> list = iOaHumanClockCountService.queryList(bo);
        list.forEach(d->{
            if (d.getStartTime()!=null){
                d.setExportStartTime(sdf.format(d.getStartTime()));
            }else {
                d.setExportStartTime("--");
            }
            if (d.getEndTime()!=null){
                d.setExportEndTime(sdf.format(d.getEndTime()));
            }else {
                d.setExportEndTime("--");
            }
        });
        ExcelUtil.exportExcel(list, "概况统计与打卡明细", OaHumanClockCountVo.class, response);
    }

    @Log(title = "日报考勤记录", businessType = BusinessType.EXPORT)
    @PostMapping("/perMonthExport")
    public void perMonthExport(OaHumanClockCountBo bo, HttpServletResponse response){
        List<OaHumanClockTotal> list = iOaHumanClockCountService.exportSumInfo(bo);
        ExcelUtil.exportExcel(list, "上下班打卡_月报", OaHumanClockTotal.class, response);
    }


    @GetMapping("/selectLastByUserId")
    public JSONObject selectLastByUserId(@RequestParam(required = false, defaultValue = "") String userId,
                                                     @RequestParam(required = false, defaultValue = "") String dateString,
                                                     @RequestParam(required = false, defaultValue = "") String nextDay){
        JSONObject jsonObject = new JSONObject();
        OaHumanClockCountVo oaHumanClockCountVo = iOaHumanClockCountService.selectLastByUserId(userId, dateString);
        jsonObject.put("data",oaHumanClockCountVo);
        OaHumanClockCountVo oaHumanClockCountVo2 = iOaHumanClockCountService.selectLastByUserId(userId, nextDay);
        if (ObjectUtil.isNotEmpty(oaHumanClockCountVo2)){
            jsonObject.put("flag",true);
        }else {
            jsonObject.put("flag",false);
        }
        return jsonObject;
    }

    @GetMapping("/getClockHistory")
    public R<List<JSONObject>> getClockHistory(@RequestParam(required = false, defaultValue = "") String userId,
                                     @RequestParam(required = false, defaultValue = "")
                                     @DateTimeFormat(pattern = "yyyy-MM-dd")
                                     @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd")
                                     Date date){
        SimpleDateFormat dateFormatIn = new SimpleDateFormat("yyyy/MM/dd");
        String format = dateFormatIn.format(date);
        OaHumanClockCountVo oaHumanClockCountVo = iOaHumanClockCountService.selectLastByUserId(userId, format);
        if (oaHumanClockCountVo==null){
            return R.ok(new ArrayList<>());
        }
        String clockList = oaHumanClockCountVo.getClockList();
        JSONArray objects = JSON.parseArray(clockList);
        if (objects!=null){
            objects.forEach(d->{
                JSONObject d1 = (JSONObject) d;
                if (oaHumanClockCountVo.getIsOutside().equals("1")){
                    d1.put("outside",true);
                }else {
                    d1.put("outside",false);
                }
                if (d1.getString("status")!=null){
                    if (d1.getString("status").contains("迟到")){
                        d1.put("status","迟到");
                    }
                    if (d1.getString("status").contains("早退")){
                        d1.put("status","早退");
                    }
                }else {
                    d1.put("status","正常");
                }
            });
        }
        List<JSONObject> list = new ArrayList<>();
        if (objects!=null){
            for (int i = 0; i < objects.size(); i++) {
                list.add(objects.getJSONObject(i));
            }
            Collections.sort(list, new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    try {
                        String type1 = o1.getString("type");
                        String type2 = o2.getString("type");
                        if (type1.equals("上班") && type2.equals("下班")) {
                            return -1; // 上班的在前面
                        } else if (type1.equals("下班") && type2.equals("上班")) {
                            return 1; // 下班的在后面
                        } else {
                            return 0; // 保持原来的顺序
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return 0;
                    }
                }
            });
        }
        return R.ok(list);
    }

    /**
     * 月报汇总概况统计
     *
     * @param id 主键
     */
//    @SaCheckPermission("oa:humanClockCount:query")
    @GetMapping("/selectSumInfo")
    public TableDataInfo<OaHumanClockTotal> selectSumInfo(OaHumanClockCountBo bo, PageQuery pageQuery) {
        return iOaHumanClockCountService.selectSumInfo( bo,pageQuery);
    }

    @GetMapping("/selectSumInfoForApp")
    public TableDataInfo<OaHumanClockTotal> selectSumInfoForApp(OaHumanClockCountBo bo, PageQuery pageQuery) {
        return iOaHumanClockCountService.selectSumInfoForApp(bo,pageQuery);
    }

    @GetMapping("/selectSumInfoByMonth")
    public R<OaHumanClockTotal> selectSumInfoByMonth( @RequestParam(required = false, defaultValue = "") String month){
        return R.ok(iOaHumanClockCountService.selectSumInfoByMonth(month));
    }

    @GetMapping("/selectSumInfoByMonthAndUserId")
    public R<OaHumanClockTotal> selectSumInfoByMonthAndUserId( @RequestParam(required = false, defaultValue = "") String month,@RequestParam(required = false, defaultValue = "") String userId){
        return R.ok(iOaHumanClockCountService.selectSumInfoByMonthAndUserId(month, userId));
    }


    @GetMapping("/selectSumInfoByDate")
    public R<OaHumanClockTotal> selectSumInfoByDate( @RequestParam(required = false, defaultValue = "")
                                                         @DateTimeFormat(pattern = "yyyy-MM-dd")
                                                         @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd")
                                                         Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String format = sdf.format(date);
        return R.ok(iOaHumanClockCountService.selectSumInfoByDate(format));
    }


//    @SaCheckPermission("oa:humanClockCount:query")
    @GetMapping("/{id}")
    public R<OaHumanClockCountVo> getInfo(@NotNull(message = "主键不能为空")
                                          @PathVariable String id) {
        return R.ok(iOaHumanClockCountService.queryById(id));
    }


//    @SaCheckPermission("oa:humanClockCount:list")
    @GetMapping("/getSumDetail")
    public TableDataInfo<Object> getSumDetail(OaHumanSelectMonthBo bo, PageQuery pageQuery) {
        return iOaHumanClockCountService.getSumDetail(bo,pageQuery);
    }

    /**
     * 新增考勤记录
     */
//    @SaCheckPermission("oa:humanClockCount:add")
    @Log(title = "考勤记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody OaHumanClockCountBo bo) {
        return toAjax(iOaHumanClockCountService.insertByBo(bo));
    }

    /**
     * 修改考勤记录
     */
//    @SaCheckPermission("oa:humanClockCount:edit")
    @Log(title = "考勤记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody OaHumanClockCountBo bo) {
        return toAjax(iOaHumanClockCountService.updateByBo(bo));
    }

    /**
     * 删除考勤记录
     *
     * @param ids 主键串
     */
//    @SaCheckPermission("oa:humanClockCount:remove")
    @Log(title = "考勤记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iOaHumanClockCountService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    public static void main(String[] args) {
//        Random random = new Random();
//        double random1 = Math.random();
//        System.out.println(random.nextInt(50));

        String yan ="no fear yan";
        String yan2 ="xiao yan";

        int a =-123;


//        System.out.println(yan.charAt(5));
//        System.out.println(yan.concat(yan2));
//        System.out.println(yan.endsWith(yan2));
//        System.out.println(yan.compareTo(yan2));
//        System.out.println(yan.indexOf("yan"));
//        System.out.println(yan.substring(8,10));
//        System.out.println(yan.toLowerCase());
//        System.out.println(yan.toUpperCase());
//        System.out.println(String.valueOf(123456789L));
//
        int[] ints = new int[10];
        List<int[]> list = Arrays.asList(ints);
//        int length = ints.length;
//        String[] a={"yan","xiao","xiao","xiao","xiao","xiao","xiao","xiao","xiao","xiao"};
//        int[] result=new int[2];
//        char c = yan2.charAt(0);
//        ArrayList<Character > objects = new ArrayList<>();
//
//        for (int anInt : ints) {
//            System.out.println(anInt);
//        }
    }
    public int lengthOfLongestSubstring(String s) {
        int count =0;
        List<Character> start =new ArrayList<>();
        for(int i =0 ;i<s.length();i++){
            int[] aa=new int[]{1,2,3,4,5,6,7,8,9,10};
            start.add(s.charAt(i));
            count++;
            for(int j=i+1;j<s.length();j++){
                if(!start.contains(s.charAt(j))){
                    return count;
                }
            }
            float a= 1;
        }
        return count;
    }

    public String addStrings(String num1, String num2) {
        int[] ad=new int[]{1,2,3,4,5,6,7,8,9,10};
        return String.valueOf(num1+num2);
    }
}
